#include "../../macro.h"
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

using std::cout;
using std::endl;

void server(char **argv)
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    ERR_CHECK(fd, -1, "socket")

    sockaddr_in sock{};
    sock.sin_addr.s_addr = inet_addr(argv[1]);
    sock.sin_port = htons(atoi(argv[2]));
    sock.sin_family = AF_INET;

    
    char buf[1024]{};
    int ret = sendto(fd, "hello", 5, 0, (sockaddr *)&sock, sizeof(sock));
    ERR_CHECK(ret, -1, "sendto")

    fd_set rdset{};
    while(1){
        bzero(buf, 1024);
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(fd, &rdset);

        ret = select(fd + 1, &rdset, nullptr, nullptr, 0);
        ERR_CHECK(ret, -1, "select")

        if(FD_ISSET(fd, &rdset)){
            ret = recvfrom(fd, buf, sizeof(buf) - 1, 0, nullptr, nullptr);
            ERR_CHECK(ret, -1, "recvfrom")

            cout << buf << endl;
        }

        if(FD_ISSET(STDIN_FILENO, &rdset)){
            ret = read(STDIN_FILENO, buf, sizeof(buf)); 
            ERR_CHECK(ret, -1, "read")

            ret = sendto(fd, buf, strlen(buf) - 1, 0, (sockaddr *)&sock, sizeof(sock));
            ERR_CHECK(ret, -1, "sendto")
        }
    }
}

int main(int argc, char *argv[])
{
    server(argv);
    return 0;
}
